<template>
  <div class="meter-form-container">
    <el-form v-loading="loading" :model="meterForm" :rules="rules" ref="meterFormRef" label-width="120px">
      <!-- 基础信息区块 -->
      <div class="section-container">
        <div class="section-header">
          <span class="section-title">基础信息</span>
          <div class="divider"></div>
        </div>

        <div class="form-item-split">
          <el-form-item prop="meter_name" label="表计名称">
            <el-input v-model="meterForm.meter_name" placeholder="请输入表计名称" style="width: 180px;" />
          </el-form-item>
          <el-form-item prop="status" label="状态">
            <el-radio-group v-model.number="meterForm.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="2">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item prop="specification" label="表计规格">
            <el-select v-model="meterForm.specification" placeholder="请选择表计规格" filterable allow-create
              style="width: 180px;">
              <el-option v-for="spec in specificationOptions" :key="spec" :label="spec" :value="spec" />
            </el-select>
          </el-form-item>
          <el-form-item prop="manufacturer" label="制造商">
            <el-input v-model="meterForm.manufacturer" placeholder="请输入制造商" style="width: 180px;" />
          </el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item prop="meter_id"
            :label="meterForm.engine_id === 7 ? '公式' : meterForm.engine_id === 19 ? '克隆表计' : '表计ID'">
            <!-- 当引擎ID为7时显示公式下拉框 - 移除.number修饰符，确保值为字符串 -->
            <el-select v-if="meterForm.engine_id === 7" v-model="meterForm.meter_id" placeholder="请选择公式"
              style="width: 180px;">
              <el-option v-for="formula in filteredFormulaList" :key="formula.id" :label="formula.name"
                :value="formula.id.toString()" />
            </el-select>
            <!-- 当引擎ID为19时显示克隆表计下拉框 -->
            <el-select clearable filterable v-else-if="meterForm.engine_id === 19" v-model="meterForm.meter_id"
              placeholder="请选择克隆表计" style="width: 180px;">
              <el-option v-for="meter in cloneMeterOptions" :key="meter.value" :label="meter.label"
                :value="meter.value" />
            </el-select>
            <!-- 其他情况下显示正常输入框 -->
            <el-input v-else v-model="meterForm.meter_id" placeholder="请输入表计ID" style="width: 180px;" />
          </el-form-item>
          <el-form-item prop="engine_id" label="引擎">
            <el-select @change="handleEngineChange" v-model.number="meterForm.engine_id" placeholder="请选择引擎" clearable
              style="width: 180px;">
              <el-option v-for="engine in engineList" :key="engine.value" :label="engine.label" :value="engine.value" />
            </el-select>
          </el-form-item>
        </div>

      </div>

      <!-- 层级信息区块 -->
      <div class="section-container">
        <div class="section-header">
          <span class="section-title">层级信息</span>
          <div class="divider"></div>
        </div>

        <div class="form-item-split">
          <el-form-item prop="meter_code" label="表计编号">
            <div style="display: flex; gap: 10px; align-items: center;">
              <el-select @change="handleLevelCodeChange" v-model="meter_level_code" placeholder="请选择表计级别"
                style="width: 100px;">
                <el-option v-for="option in levelCodeOptions" :key="option" :label="option" :value="option" />
              </el-select>
              <span>-</span>
              <el-input v-model="meter_seq_code" style="width: 80px;"></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="parent_id" label="父级表计">
            <el-select @change="handleParentChange" filterable v-model="meterForm.parent_id" placeholder="请选择父级表计"
              style="width: 180px;">
              <el-option v-for="meter in parentList" :key="meter.value" :label="meter.label" :value="meter.value" />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <!-- 安装信息区块 -->
      <div class="section-container">
        <div class="section-header">
          <span class="section-title">安装信息</span>
          <div class="divider"></div>
        </div>

        <div class="form-item-split">
          <el-form-item label="安装位置" prop="installation_location">
            <el-input v-model="meterForm.installation_location" placeholder="请输入安装位置" style="width: 180px;" />
          </el-form-item>
          <el-form-item label="安装日期" prop="installation_date">
            <el-date-picker v-model="meterForm.installation_date" type="date" placeholder="请选择安装日期"
              style="width: 180px;" />
          </el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item label="供应点位" prop="supply_region">
            <el-input v-model="meterForm.supply_region" placeholder="请输入供应点位" style="width: 180px;" />
          </el-form-item>
          <el-form-item></el-form-item>
        </div>
      </div>

      <!-- 计量信息区块 -->
      <div class="section-container">
        <div class="section-header">
          <span class="section-title">计量信息</span>
          <div class="divider"></div>
        </div>

        <div class="form-item-split">
          <el-form-item label="启表底数" prop="bottom_value">
            <el-input v-model.number="meterForm.bottom_value" type="number" placeholder="请输入启表底数"
              style="width: 180px;" />
          </el-form-item>
          <el-form-item label="标煤系数" prop="standard_coal_factor">
            <el-select v-model="meterForm.standard_coal_factor" placeholder="请输入或选择折标煤系数" filterable allow-create
              style="width: 180px;">
              <el-option v-for="factor in STANDARD_COAL_FACTORS" :key="factor.value"
                :label="`${factor.label} (${factor.value})`" :value="factor.value" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item label="倍率" prop="multiple">
            <el-input v-model.number="meterForm.multiple" type="number" placeholder="请输入倍率" style="width: 180px;" />
          </el-form-item>
          <el-form-item prop="check_no_record" label="纳入离线统计">
            <el-switch v-model="meterForm.check_no_record" inline-prompt active-text="是" inactive-text="否" />
          </el-form-item>
          <el-form-item v-if="meterForm.type === 1" label="参与漏水统计" prop="is_drain_considerd">
            <el-switch v-model="meterForm.is_drain_considerd" inline-prompt active-text="是" inactive-text="否" />
          </el-form-item>
        </div>

        <div class="form-item-split" v-if="meterForm.type === 1">
          <el-form-item label="最低流量" prop="min_value">
            <el-input v-model="meterForm.min_value" placeholder="低于此流量不计入漏损" style="width: 180px;">
              <template #suffix>
                <span style="color: #909399;">m³</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item></el-form-item>
        </div>

        <!-- 电表专属选项 -->
        <div class="form-item-split" v-if="meterForm.type === 2">
          <el-form-item label="电表类型" prop="elec_generate">
            <el-radio-group v-model.number="meterForm.elec_generate">
              <el-radio :value="1">发电</el-radio>
              <el-radio :value="2">售电</el-radio>
              <el-radio :value="3">供电</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="meterForm.elec_generate === 1" label="新能源" prop="new_energy">
            <el-input v-model="meterForm.new_energy" placeholder="请输入新能源" style="width: 180px;" />
          </el-form-item>
        </div>
      </div>

      <!-- 统计标签区块 -->
      <div class="section-container">
        <div class="section-header">
          <span class="section-title">统计标签</span>
          <div class="divider"></div>
        </div>

        <div class="form-item-split">
          <el-form-item label="楼栋" prop="cell">
            <el-select clearable v-model="meterForm.cell" placeholder="请选择楼栋" filterable allow-create
              style="width: 180px;">
              <el-option v-for="cell in cellOptions" :key="cell" :label="cell" :value="cell" />
            </el-select>
          </el-form-item>
          <el-form-item label="用途" prop="sub_category">
            <el-select v-model="meterForm.sub_category" filterable allow-create clearable placeholder="请选择或创建用途"
              style="width: 180px;">
              <el-option-group v-for="(options, group) in groupedCategoryOptions" :key="group" :label="group">
                <el-option v-for="option in options" :key="option" :label="option" :value="option" />
              </el-option-group>
              <el-option v-for="option in ungroupedCategories" :key="option" :label="option" :value="option" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item label="区域" prop="area_id">
            <el-select filterable v-model.number="meterForm.area_id" clearable placeholder="请选择区域"
              style="width: 180px;">
              <el-option v-for="area in avaliableAreaList" :key="area.id" :label="area.name" :value="area.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="用能户" prop="energy_user_id">
            <el-select v-model="meterForm.energy_user_id" clearable placeholder="请选择用能户" style="width: 180px;">
              <el-option v-for="user in energyUserList" :key="user.id" :label="user.name" :value="user.id" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item label=" 能源类别" prop="meter_type">
            <el-select v-model="meterForm.meter_type" filterable allow-create clearable placeholder="请选择或创建水源类型"
              style="width: 180px;">
              <el-option v-for="option in meterTypeOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>

          <el-form-item></el-form-item>
        </div>

        <div class="form-item-split">
          <el-form-item label="重点设备" prop="is_important_device">
            <el-switch v-model="meterForm.is_important_device" inline-prompt active-text="是" inactive-text="否" />
          </el-form-item>
          <el-form-item v-if="meterForm.is_important_device" label="设备名称" prop="important_device_name">
            <el-input v-model="meterForm.important_device_name" placeholder="请输入重点设备名称" style="width: 180px;" />
          </el-form-item>
          <el-form-item v-else></el-form-item>
        </div>
      </div>

      <!-- 备注信息区块 -->
      <div class="section-container">
        <div class="section-header">
          <span class="section-title">备注信息</span>
          <div class="divider"></div>
        </div>

        <div class="form-item-full">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="meterForm.remarks" type="textarea" :rows="4" placeholder="请输入备注信息" />
          </el-form-item>
        </div>
      </div>

      <!-- 按钮区域 -->
      <div class="form-buttons">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onReset">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { addMeterApi, getMeterInfoApi, updateMeterApi } from "@/api/meter";
import { useMeterStore } from "@/stores/meter";
import { useCompanyStore } from "@/stores/company";
import { useAreaStore } from "@/stores/area";
import { getNextSubCode, getNextSequence } from "@/utils/getNextSubCode";
import { getFormulaList } from "@/utils/formula";
import { handleError } from "@/utils/handleError";
import { STANDARD_COAL_FACTORS, engineList } from "@/constants";
import rule from "./meterDialog/rule";
import { getEnergyUsersApi } from "../../api/energy_users";
import { categoryMap, meterTypeMap } from "../../constants";
import { getFormulaApi } from "../../api/formula";
const meterStore = useMeterStore();
const companyStore = useCompanyStore();
const areaStore = useAreaStore();
onMounted(async () => {
  const res = await getFormulaApi(
    companyStore.currentCompany.id,
  )
  console.log(res);

})
// 定义loading状态
const loading = ref(false);

// 定义表单数据
const meterForm = ref({
  parent_id: null,
  company_id: companyStore.currentCompany.id,
  engine_id: null,
  type: meterStore.currentSelectedType,
  meter_code: "",
  meter_name: "", // 新增表计名称字段
  meter_id: "",
  installation_date: "",
  manufacturer: "",
  specification: "",
  standard_coal_factor: 0,
  area_id: null,
  supply_region: "",
  is_drain_considerd: true,
  status: "1",
  remarks: "",
  bottom_value: 0,
  multiple: 1,
  installation_location: "",
  sub_category: "",
  meter_type: "", // 能源类别字段
  check_no_record: true, // 新增是否检测离线字段，默认为true

  // 新增通用字段
  cell: "", // 楼栋
  is_important_device: false, // 是否重点设备
  important_device_name: "", // 重点设备名称
  energy_user_id: null, // 用能户

  // 水表专属字段
  min_value: "", // 最低流量，低于此流量不计入漏损，字符串类型如 "1.0"

  // 电表专属字段 - 修改为三种状态
  elec_generate: 3, // 默认为3(供电)，可选值: 1(发电), 2(售电), 3(供电)
  new_energy: "", // 新能源类型
});

// 能源类别选项（根据type不同而变化）
const meterTypeOptions = computed(() => {
  switch (meterForm.value.type) {
    case 1: // 水表
      return meterTypeMap.water;
    case 2: // 电表
      return meterTypeMap.elec;
    case 3: // 气表
      return meterTypeMap.gas;
    default:
      return [];
  }
});

// 根据表计类型筛选公式列表
const filteredFormulaList = computed(() => {
  if (!formulaList.value) return [];

  // 根据当前表计类型确定公式类型
  let usageType = "";
  switch (meterForm.value.type) {
    case 1: // 水表
      usageType = "水虚拟表";
      break;
    case 2: // 电表
      usageType = "电虚拟表";
      break;
    case 3: // 气表
      usageType = "气虚拟表";
      break;
    case 6: // 压力表
      usageType = "压力虚拟表";
      break;
    default:
      usageType = "";
  }

  // 过滤出匹配的公式
  return formulaList.value.filter(formula => formula.usage === usageType);
});

const energyUserList = ref([]);

// 新增可选表计列表
const cloneMeterOptions = computed(() => {
  return meterStore.meterList
    .filter(meter => meter.type === meterForm.value.type)
    .map(meter => ({
      label: meter.meter_code,
      value: meter.id.toString()
    }));
});

// 设置能源类别默认值的函数
const setDefaultMeterType = () => {
  if (!meterForm.value.meter_type) {
    switch (meterForm.value.type) {
      case 1: // 水表
        meterForm.value.meter_type = "自来水";
        break;
      case 2: // 电表
        meterForm.value.meter_type = "商业用电";
        // 强制电表类型为供电
        meterForm.value.elec_generate = 3;
        break;
      case 3: // 气表
        meterForm.value.meter_type = "商业用气";
        break;
      default:
        meterForm.value.meter_type = "";
    }
  }
  // 如果是电表，强制elec_generate为3
  if (meterForm.value.type === 2) {
    meterForm.value.elec_generate = 3;
  }
};

// 当type变化时，设置默认的meter_type和电表特有字段默认值
watch(() => meterForm.value.type, (newType) => {
  setDefaultMeterType();

  // 如果是电表，强制elec_generate为3
  if (newType === 2) {
    meterForm.value.elec_generate = 3;
  }
});

// 定义预设用途分类
const PRESET_CATEGORIES = categoryMap

// 将分组类别转换为扁平数组，用于选择组件
const getAllPresetCategories = () => {
  const allCategories = [];
  for (const group in PRESET_CATEGORIES) {
    for (const category of PRESET_CATEGORIES[group]) {
      allCategories.push(category);
    }
  }
  return allCategories;
};

// 更新categoryOptions ref使用分组选项
const categoryOptions = ref([]);
const groupedCategoryOptions = computed(() => {
  // 创建一个新的结果对象
  const result = {};

  // 首先添加"无"选项作为独立的分组
  result['基础'] = ['无'];

  // 获取所有预设分类作为扁平数组
  const allPresetCategories = getAllPresetCategories();

  // 找出不在预设分类中的自定义分类，并去重
  const customCategories = [...new Set(
    categoryOptions.value.filter(category => !allPresetCategories.includes(category) && category !== '无')
  )];

  // 添加自定义分类组
  if (customCategories.length > 0) {
    result['自定义'] = customCategories;
  }

  // 然后添加其他预设分类组
  for (const group in PRESET_CATEGORIES) {
    if (group !== '自定义') {  // 跳过自定义组，因为我们已经单独处理了
      result[group] = [...PRESET_CATEGORIES[group]];
    }
  }

  return result;
});

// 未分组的类别
const ungroupedCategories = computed(() => {
  return []; // 此处可以根据需要添加未分组的类别
});

const fetchAllCategories = async () => {
  try {
    // 从现有表计中获取用途
    const existingCategories = meterStore.meterList
      .map((meter) => meter.sub_category)
      .filter((category) => category && category.trim() !== "");

    // 确保结果没有重复项
    categoryOptions.value = [...new Set(existingCategories)];
  } catch (error) {
    handleError(error, "获取用途数据失败", true);
  }
};

const avaliableAreaList = computed(() => {
  return [
    { id: -1, name: "无" },
    ...areaStore.areas.map(item => {
      return { id: item.id, name: item.name };
    })
  ]
});

// 定义响应式变量
let meter_level_code = computed({
  get: () => {
    return meterForm.value.meter_code.split("-")[0];
  },
  set: (val) => {
    const parts = meterForm.value.meter_code.split("-");
    meterForm.value.meter_code = `${val}-${parts[1] || "01"}`;
  },
});
let meter_seq_code = computed({
  get: () => {
    return meterForm.value.meter_code.split("-")[1];
  },
  set: (val) => {
    const parts = meterForm.value.meter_code.split("-");
    meterForm.value.meter_code = `${parts[0]}-${val}`;
  },
});

const parentList = computed(() => [
  { value: 0, label: "无" },
  ...meterStore.meterList.map((item) => {
    if (meterForm.value.meter_code === item.meter_code) return false
    return {
      value: item.id,
      label: item.meter_code,
    }
  }).filter(item => item),
]);

function handleParentChange(val) {
  // 获取当前表计编号的层级
  const currentLevel = meterForm.value.meter_code.split('-')[0];
  // 获取新选择的父级表计
  const parentMeter = parentList.value.find((item) => item.value === val);
  if (!parentMeter) return;

  // 获取父级表计的编号
  const parentCode = parentMeter.label;
  // 如果父级是"无"，则使用当前层级
  if (parentCode === "无") {
    meterForm.value.parent_id = -1; // 父级为无时设置parent_id为-1
    meterForm.value.meter_code = `${currentLevel}-01`;
    return;
  }

  // 获取父级表计的层级
  const parentLevel = parentCode.split('-')[0];

  // 检查当前表计是否已经是下一级
  const isAlreadyNextLevel = (() => {
    // 如果是水表
    if (meterForm.value.type === 1) {
      const currentIndex = BASE_LEVEL_CODES.indexOf(currentLevel);
      const parentIndex = BASE_LEVEL_CODES.indexOf(parentLevel);
      return currentIndex === parentIndex + 1;
    }
    // 如果是电表
    if (meterForm.value.type === 2) {
      const currentIndex = BASE_LEVEL_CODES.indexOf(currentLevel.replace('D', ''));
      const parentIndex = BASE_LEVEL_CODES.indexOf(parentLevel.replace('D', ''));
      return currentIndex === parentIndex + 1;
    }
    // 如果是气表
    if (meterForm.value.type === 3) {
      const currentIndex = BASE_LEVEL_CODES.indexOf(currentLevel.replace('Q', ''));
      const parentIndex = BASE_LEVEL_CODES.indexOf(parentLevel.replace('Q', ''));
      return currentIndex === parentIndex + 1;
    }
    // 如果是压力表
    if (meterForm.value.type === 6) {
      const currentIndex = BASE_LEVEL_CODES.indexOf(currentLevel.replace('Y', ''));
      const parentIndex = BASE_LEVEL_CODES.indexOf(parentLevel.replace('Y', ''));
      return currentIndex === parentIndex + 1;
    }
    return false;
  })();

  // 如果已经是下一级，则不改变表计编号
  if (isAlreadyNextLevel) {
    return;
  }

  // 如果不是下一级，则生成新的表计编号
  let autoMeterCode = getNextSubCode(
    parentCode,
    meterStore.meterList.map((item) => item.meter_code)
  ) || "";
  meterForm.value.meter_code = autoMeterCode;
}

// engine_id 变化时的处理
function handleEngineChange(val) {
  if (val === 10) {
    meterForm.value.parent_id = -1;
    meterForm.value.standard_coal_factor = 0;
    meterForm.value.meter_id = "";
  } else if (val === 7) {
    // 虚拟表公式引擎处理逻辑
    meterForm.value.meter_id = ""; // 重置表计ID为空字符串，确保是字符串类型

    // 确保已加载公式列表
    if (formulaList.value.length === 0) {
      getFormulaList(companyStore.currentCompany.id).then(formulas => {
        formulaList.value = formulas;
      });
    }
  }
}

const BASE_LEVEL_CODES = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ",];

const levelCodeOptions = computed(() => {
  const type = meterForm.value.type;
  switch (type) {
    case 1: // 水表
      return BASE_LEVEL_CODES;
    case 2: // 电表
      return BASE_LEVEL_CODES.map((code) => `D${code}`);
    case 3: // 气表
      return BASE_LEVEL_CODES.map((code) => `Q${code}`);
    case 6: // 压力表
      return BASE_LEVEL_CODES.map((code) => `Y${code}`);
    default:
      return [];
  }
});

function handleLevelCodeChange(val) {
  if (val === "") {
    meter_seq_code.value = "01";
  } else {
    meter_seq_code.value =
      getNextSequence(val, meterStore.meterList.map((item) => item.meter_code)) ||
      "01";
  }
}

// 表计规格选项（从现有表计中获取唯一值）
const specificationOptions = computed(() => {
  const specs = meterStore.meterList.map(meter => meter.specification).filter(spec => spec);
  return [...new Set(specs)];
});

// 楼栋选项（从现有表计中获取唯一值）
const cellOptions = computed(() => {
  const cells = meterStore.meterList.map(meter => meter.cell).filter(cell => cell);
  return [...new Set(cells)];
});

// 定义验证规则 (需要更新规则以包含新字段)
const rules = rule

// 获取表单引用
const meterFormRef = ref(null);

// 提交表单
const onSubmit = () => {
  meterFormRef.value.validate(async (valid) => {
    if (valid) {
      await submitValid();
    } else {
      ElMessage.error("请正确填写表单。");
      return false;
    }
  });
};

// 重置表单
const onReset = () => {
  if (meterFormRef.value) {
    meterFormRef.value.resetFields();
    // 生成自动表计编码
    let autoMeterCode =
      getNextSubCode(
        props.pMeter.meter_code,
        meterStore.meterList.map((item) => item.meter_code)
      ) || "";
    // 重置表单数据到初始值
    meterForm.value = {
      id: null,
      parent_id: !props.id && !props.pMeter.id ? 0 : (props.pMeter.id ? Number(props.pMeter.id) : null),
      company_id: companyStore.currentCompany.id,
      engine_id: props.pMeter.engine_id ? Number(props.pMeter.engine_id) : null,
      type: props.pMeter.type
        ? Number(props.pMeter.type)
        : meterStore.currentSelectedType,
      meter_code: autoMeterCode,
      meter_name: "", // 重置表计名称
      meter_id: "",
      bottom_value: 0,
      standard_coal_factor: 0,
      multiple: 1,
      installation_date: "",
      manufacturer: "",
      specification: "",
      area_id: null,
      supply_region: "",
      is_drain_considerd: true,
      status: "1",
      remarks: "",
      installation_location: "",
      sub_category: "",
      meter_type: "", // 重置能源类别字段
      check_no_record: true, // 重置是否检测离线为true

      // 重置新增通用字段
      cell: "",
      is_important_device: false,
      important_device_name: "",
      energy_user_id: null,

      // 重置水表专属字段
      min_value: "", // 字符串类型

      // 重置电表专属字段
      elec_generate: 3, // 强制为供电(3)
      new_energy: "",
    };

    // 设置能源类别默认值
    setDefaultMeterType();
    // 如果是电表，强制elec_generate为3
    if (meterForm.value.type === 2) {
      meterForm.value.elec_generate = 3;
    }
  }
};

// 提交验证 - 修改处理meter_id类型
const submitValid = async () => {
  loading.value = true;
  try {
    meterForm.value.engine_id = Number(meterForm.value.engine_id);

    // 确保meter_id为字符串类型
    if (meterForm.value.engine_id === 7 && meterForm.value.meter_id !== null) {
      // 对于虚拟表公式，确保meter_id是字符串
      meterForm.value.meter_id = String(meterForm.value.meter_id);
    } else if (
      meterForm.value.engine_id === 10 &&
      Array.isArray(meterForm.value.meter_id)
    ) {
      // 原有的多选meter_id处理逻辑保持不变
      meterForm.value.meter_id = meterForm.value.meter_id.join(",");
    } else if (meterForm.value.engine_id === 19 && meterForm.value.meter_id !== null) {
      meterForm.value.meter_id = String(meterForm.value.meter_id);
    }

    let res = {};
    if (!props.id) {
      res = await addMeterApi(meterForm.value);
    } else {
      res = await updateMeterApi(meterForm.value);
    }
    ElMessage.success("操作成功");
    meterStore.fetchMeterList({
      type: meterStore.currentSelectedType,
    });
    emit("update:visible");
    emit("success");
  } catch (error) {
    handleError(error, "操作失败", true);
  } finally {
    loading.value = false;
  }
};

// 获取表计详情
const fetchMeterDetail = async (id) => {
  loading.value = true;
  try {
    const res = await getMeterInfoApi({ id });
    if (res.code !== 200) {
      console.error(res.message);
      ElMessage.error(res.message);
    } else {
      const data = res.data[0];
      if (data.engine_id === 10 && typeof data.meter_id === "string") {
        data.meter_id = data.meter_id.split(",").map((id) => Number(id));
      }
      meterForm.value = {
        ...data,
        parent_id: Number(data.parent_id),
        company_id: Number(data.company_id),
        engine_id: Number(data.engine_id),
        type: Number(data.type),
        status: Number(data.status),
        installation_date: data.installation_date
          ? new Date(data.installation_date)
          : "",
        sub_category: data.sub_category || "",
        meter_type: data.meter_type || "", // 确保meter_type字段正确赋值
        meter_name: data.meter_name || "", // 确保表计名称字段正确赋值
        check_no_record: data.check_no_record === undefined ? true : data.check_no_record, // 确保离线检测字段正确赋值

        // 确保新字段有默认值
        cell: data.cell || "",
        is_important_device: data.is_important_device || false,
        important_device_name: data.important_device_name || "",
        energy_user_id: data.energy_user_id || null,

        // 水表专属字段 - 保持字符串类型
        min_value: data.min_value || "",

        // 修改电表专属字段处理
        elec_generate: data.elec_generate !== undefined ? Number(data.elec_generate) : 3,
        new_energy: data.new_energy || "",
      };

      // 如果没有meter_type，则设置默认值
      if (!data.meter_type) {
        setDefaultMeterType();
      }

      // 从现有表计中提取唯一的用途
      if (data.sub_category && !categoryOptions.value.includes(data.sub_category)) {
        categoryOptions.value.push(data.sub_category);
      }
    }
  } catch (err) {
    console.error(err);
    ElMessage.error(err.message || "获取表计信息失败");
  } finally {
    loading.value = false;
  }
};

// 获取用能户列表的函数
const fetchEnergyUsers = async () => {
  try {
    const res = await getEnergyUsersApi({
      company_id: companyStore.currentCompany.id
    })
    energyUserList.value = res.data;
  } catch (error) {
    handleError(error, "获取用能户数据失败", true);
  }
};

// 定义props
const props = defineProps({
  pMeter: {
    type: Object,
    default: () => ({}),
  },
  id: {
    type: Number,
    default: null,
  },
});

// 定义emit
const emit = defineEmits(["update:visible", "success"]);

// 监听 props.pMeter 的变化
watch(
  () => props.pMeter,
  (newPMeter) => {
    meterForm.value.parent_id = newPMeter.id ? Number(newPMeter.id) : null;
    meterForm.value.type =
      newPMeter.type !== undefined
        ? Number(newPMeter.type)
        : meterStore.currentSelectedType;

    // 当type变化时，设置默认的meter_type
    setDefaultMeterType();

    // 新增时且为电表，强制elec_generate为3
    if (!props.id && meterForm.value.type === 2) {
      meterForm.value.elec_generate = 3;
    }
  },
  { deep: true }
);


const formulaList = ref([]);

// onMounted 钩子
onMounted(async () => {
  if (!areaStore.areas.length) {
    await areaStore.fetchAreas();
  }
  formulaList.value = await getFormulaList(
    companyStore.currentCompany.id,
  );

  // 获取所有用途选项
  await fetchAllCategories();

  // 获取用能户列表
  await fetchEnergyUsers();

  // 如果是编辑模式
  if (props.id) {
    await fetchMeterDetail(props.id);
  } else {
    onReset();
    // 设置能源类别默认值
    setDefaultMeterType();
  }
});
</script>

<style scoped>
.section-container {
  background-color: #fff;
  padding: 0 var(--gap-normal);
}

.section-header {
  margin-bottom: 20px;
  position: relative;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.divider {
  height: 1px;
  background-color: #EBEEF5;
  margin-top: 10px;
}

.form-item-split {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.form-item-split .el-form-item {
  flex: 1;
  margin-right: 20px;
}

.form-item-split .el-form-item:last-child {
  margin-right: 0;
}

.form-buttons {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.form-buttons .el-button {
  min-width: 120px;
  margin: 0 10px;
}

/* 保持用途选择器的宽度 */
.el-select {
  width: 100%;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}
</style>